
import axios from 'axios';
import { request, API_BASE_URL, getRefreshTokenFromCookie } from '@/utils/http';
import { storage } from '@/utils/storage';

// 登录参数类型定义：支持手机号验证码登录和账号密码登录两种方式
export type LoginPhoneParams = { phone: string; smsCode: string; loginType?: number };
export type LoginPasswordParams = { account: string; password: string; loginType?: number };
export type LoginParams = LoginPhoneParams | LoginPasswordParams;
// 注册接口
export const register = async (data: { phone: string; smsCode: string; name: string; account: string; password: string }) => {
  try {
    return await request(`${API_BASE_URL}/OA/user/register`, {
      method: 'POST',
      data: data,
    });
  } catch (error) {
    console.error('注册请求失败:', error);
  }
};



// 重置密码接口
export const resetPassword = async (data: { phone: string; smsCode: string; newPassword: string }) => {
  try {
    return await request(`${API_BASE_URL}/OA/user/updatePassword`, {
      method: 'POST',
      data: data,
    });
  } catch (error) {
    console.error('重置密码请求失败:', error);
    throw error;
  }
};

// 发送验证码接口 
export const sendSmsCode = async (data: { phone: string }) => {
  try {
    return await request(`${API_BASE_URL}/OA/user/sendCode`, {
      method: 'POST',
      data: data,
    });
  } catch (error) {
    console.error('发送验证码失败:', error);
  }
};

// 登录接口
export const loginApi = async (data: LoginParams) => {
  try {
    const response = await request(`${API_BASE_URL}/OA/user/login`, {
      method: 'POST',
      data: data,
    });
    
    console.log('登录响应数据:', response);
    console.log('登录后的cookie:', document.cookie);
    console.log('=== 登录接口调试结束 ===');
    
    return response;
  } catch (error) {
    console.error('登录请求失败:', error);
    throw error;
  }
};

// 刷新token接口 - 使用独立的axios实例避免拦截器循环调用
export const refreshTokenApi = async () => {
  try {
    console.log('refreshTokenApi: 开始刷新token');
    
    // 获取refreshToken
    const refreshToken = getRefreshTokenFromCookie();
    console.log('refreshTokenApi: 获取到的refreshToken:', refreshToken ? '存在' : '不存在');
    
    if (!refreshToken) {
      throw new Error('未找到refreshToken，无法刷新token');
    }
    
    // 创建独立的axios实例，避免拦截器循环调用
    const refreshAxios = axios.create({
      timeout: 10000,
      withCredentials: true, // 确保发送cookies
      headers: {
        'Content-Type': 'application/json',
      },
    });
    
    // 在请求体中发送refreshToken
    const requestBody = {
      refreshToken: refreshToken
    };
    
    console.log('refreshTokenApi: 发送刷新请求到', `${API_BASE_URL}/OA/user/refresh`);
    console.log('refreshTokenApi: 请求体:', requestBody);
    
    const response = await refreshAxios.post(`${API_BASE_URL}/OA/user/refresh`, requestBody);
    // 检查响应是否包含新的accessToken
    if (response.data && response.data.accessToken) {
      console.log('refreshTokenApi: 成功获取新的accessToken');
      return response;
    } else {
      console.error('refreshTokenApi: 响应中未找到accessToken');

         // 检查响应数据中的code字段，处理token非法情况
  
      throw new Error('刷新token响应格式错误：未找到accessToken');
    }
  } catch (error: any) {
     // 可以在这里触发跳转到登录页 
    console.error('refreshTokenApi: 刷新token失败:', error);
    console.error('refreshTokenApi: refreshToken已过期，需要重新登录');
    // 清除所有本地token
    storage.removeItem('accessToken');
    storage.removeItem('refreshToken');

    // window.location.href = '/login';
    
    throw error;
  }
};

// 获取用户信息
export const getUserInfo = async () => {
  try {
    return await request(`${API_BASE_URL}/user/info`, {
      method: 'GET',
    });
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
};

// 费用相关接口
export const getExpenseList = async (params?: any) => {
  try {
    const queryString = params ? '?' + new URLSearchParams(params).toString() : '';
    return await request(`${API_BASE_URL}/expense/list${queryString}`, {
      method: 'GET',
    });
  } catch (error) {
    console.error('获取费用列表失败:', error);
  }
};

export const getExpenseDetail = async (id: string) => {
  try {
    return await request(`${API_BASE_URL}/expense/detail/${id}`, {
      method: 'GET',
    });
  } catch (error) {
    console.error('获取费用详情失败:', error);

  }
};

// 文件上传接口
export const uploadFile = async (file: File) => {
  try {
    // 创建FormData对象
    const formData = new FormData();
    // 后端接口参数名为'files'，附带文件名以提升兼容性
    const fileName = (file as any).name || 'upload';
    formData.append('files', file, fileName);
    
    // 调用上传接口
    // 让axios自动设置multipart边界，避免手动设置Content-Type导致边界错误
    const resp = await request(`${API_BASE_URL}/OA/file/upload`, {
      method: 'POST',
      data: formData,
    });

    // 统一解析返回的文件路径，兼容多种格式
    const pickPathFromString = (s: string | undefined) => {
      if (!s || typeof s !== 'string') return undefined;
      const str = s.trim();
      if (str.startsWith('http://') || str.startsWith('https://')) return str;
      if (str.startsWith('/')) return str;
      const match = str.match(/(\/(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+(?:\.[A-Za-z0-9._-]+)?)/);
      return match ? match[1] : undefined;
    };

    const extractPath = (r: any): string | undefined => {
      try {
        if (typeof r === 'string') return pickPathFromString(r) ?? r;
        const payload = r?.data !== undefined ? r.data : r;
        if (typeof payload === 'string') return pickPathFromString(payload) ?? payload;
        if (Array.isArray(payload)) {
          const first = payload.find((x) => typeof x === 'string')
            || payload.find((x) => x && (x.path || x.url));
          if (typeof first === 'string') return first;
          if (first?.path) return first.path;
          if (first?.url) return first.url;
        }
        if (payload && typeof payload === 'object') {
          if (payload.path) return payload.path;
          if (payload.url) return payload.url;
          if (Array.isArray(payload.paths) && payload.paths.length) return payload.paths[0];
          if (Array.isArray(payload.urls) && payload.urls.length) return payload.urls[0];
        }
        if (r?.path) return r.path;
        if (r?.url) return r.url;
        if (typeof r?.msg === 'string') {
          const p = pickPathFromString(r.msg);
          if (p) return p;
        }
      } catch (e) {
        // ignore
      }
      return undefined;
    };

    const normalized = { ...resp } as any;
    normalized.path = extractPath(resp);
    return normalized;
  } catch (error) {
    console.error('文件上传失败:', error);
    throw error;
  }
};

// 文件下载接口
export const downloadFile = async (filePath: string, fileName?: string) => {
  try {
    // 使用文件路径进行下载
    const response = await request(`${API_BASE_URL}/OA/file/download`, {
      method: 'POST',
      data: {
        path: filePath, // 传递文件路径给后端
      },
      responseType: 'blob', // 设置响应类型为blob
    });
    // 兼容处理：当responseType为blob时，request会返回AxiosResponse
    const blobData = (response && response.data) ? response.data : response;
    const blob = blobData instanceof Blob ? blobData : new Blob([blobData]);
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName || filePath.split('/').pop() || 'download';
    link.style.display = 'none';
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    // 释放URL对象
    window.URL.revokeObjectURL(url);
    
    return response;
  } catch (error) {
    console.error('文件下载失败:', error);
    throw error;
  }
};

// 获取文件预览URL接口
export const getFilePreviewUrl = async (filePath: string) => {
  try {
    // 构建文件预览URL，使用后端返回的path
    return `${API_BASE_URL}/OA/file/download?path=${encodeURIComponent(filePath)}`;
  } catch (error) {
    console.error('获取文件预览URL失败:', error);
    throw error;
  }
};

// 通过接口获取文件Blob并生成可用于<img>/iframe的本地预览URL（解决需要token时直接访问报401的问题）
export const getFilePreviewBlobUrl = async (filePath: string) => {
  try {
    const response = await request(`${API_BASE_URL}/OA/file/download`, {
      method: 'GET',
      params: { path: filePath },
      responseType: 'blob',
    });
    const blobData = (response && response.data) ? response.data : response;
    const blob = blobData instanceof Blob ? blobData : new Blob([blobData]);
    const url = window.URL.createObjectURL(blob);
    return url;
  } catch (error) {
    console.error('获取文件预览Blob失败:', error);
    throw error;
  }
};